package com.javaweb.admin.config;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.javaweb.admin.entity.NcTaskLog;
import com.javaweb.admin.entity.Scheduled;
import com.javaweb.admin.entity.SysMsfxYjbg;
import com.javaweb.admin.entity.filenameRule.InvoiceDownloadView;
import com.javaweb.admin.entity.filenameRule.SaleinvoiceDownload;
import com.javaweb.admin.mapper.SaleinvoiceDownloadMapper;
import com.javaweb.admin.mapper.ScheduledMapper;
import com.javaweb.admin.mapper.SysMsfxYjbgMapper;
import com.javaweb.admin.service.AbstractJob;
import com.javaweb.admin.service.INcTaskLogService;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.utils.DateUtils;
import com.shyp.daodikeji.GatewayAddressData;
import com.shyp.daodikeji.SHYPUtil;
import com.shyp.daodikeji.YonyouInvoiceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DownloadInvoiceJob extends AbstractJob {
    @Autowired
    ScheduledMapper scheduledMapper;

    @Autowired
    INcTaskLogService iNcTaskLogService;

    @Autowired
    SaleinvoiceDownloadMapper saleinvoiceDownloadMapper;

    @Override
    public String getName() {
        QueryWrapper<Scheduled> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classpath", this.getClass().getName());
        Scheduled entity = scheduledMapper.selectOne(queryWrapper);
        return entity.getName();
    }

    @Override
    public void execute() {
        NcTaskLog taskLog = new NcTaskLog();
        taskLog.setTaskType("下载电子发票");
        taskLog.setBillCount(0);
        taskLog.setStartTime(DateUtils.now());
        String material_code = "";
        String batch_code = "";
        List<InvoiceDownloadView> downList = saleinvoiceDownloadMapper.getInvoiceDownloadList();
        GatewayAddressData data = SHYPUtil.getGatewayAddress("agczee5o");
        String token = SHYPUtil.getToken(data.getTokenUrl());
        String url = data.getGatewayUrl();
        url+="/yonbip/tax/output-tax/api/einvoice/getbsfile?access_token="+token;
        String savePath = CommonConfig.yonyouInvoicePath;
        SaleinvoiceDownload entity = new SaleinvoiceDownload();
        Map<String,Object> param = new HashMap<>();
        for (InvoiceDownloadView item : downList) {
            savePath = CommonConfig.yonyouInvoicePath;
            savePath+=item.getCustcode()+"\\"+item.getDbilldate();
            File dests = new File(savePath);
            if (!dests.exists()) {
                dests.mkdirs();
            }
            String invoiceNo = item.getVgoldtaxcode();
            String body="{\n" +
                    "        \"nsrsbh\": \"91310108703137513R\",\n" +
                    "        \"fplx\": \"32\",\t\n" +
                    "        \"slfphm\": \""+invoiceNo+"\",\n" +
                    "        \"taxpdf\": \"1\",\n" +
                    "        \"taxofd\": \"1\",\n" +
                    "        \"taxxml\": \"1\"\n" +
                    "    }";
            String result = HttpUtil.post(url.toString(),body);
            YonyouInvoiceResult invoiceResult = JSON.parseObject(result,YonyouInvoiceResult.class);
            savePath = CommonConfig.yonyouInvoicePath;
            String pdfFile = item.getCustcode()+"\\"+item.getDbilldate()+"\\"+invoiceNo+"_taxpdf.pdf";
            if(invoiceResult.getCode().equals("200")){
                boolean downSuccess= SHYPUtil.Base64ToFile(invoiceResult.getData().getTaxpdf(),savePath+pdfFile);
                //发票pdf下载成功后写下载记录表
                if(downSuccess){
                    entity.setCustcode(item.getCustcode());
                    entity.setDbilldate(item.getDbilldate());
                    entity.setVbillcode(item.getVgoldtaxcode());
                    entity.setPdffilename(pdfFile);
                    param.clear();
                    param.put("vbillcode",item.getVgoldtaxcode());
                    param.put("custcode",item.getCustcode());
                    if(saleinvoiceDownloadMapper.selectByMap(param).size()==0) {
                        saleinvoiceDownloadMapper.insert(entity);
                    }

                }
            }

        }
        taskLog.setBillNo("");
        taskLog.setEndTime(DateUtils.now());
        iNcTaskLogService.save(taskLog);

    }
}

